package com.example.common.basecontroller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import com.example.common.constants.RESTFUL_COMMON_KEY;
import com.example.common.dto.ContentModel;
import com.example.common.dto.ResultModel;
import com.example.common.dto.UserModel;
import org.apache.commons.lang.StringUtils;


/**
 * @author ：czx
 * @date ：Created in 2021/6/24 15:43
 * @modified By：
 */
@Slf4j
public class BaseController {

    public ResultModel resultResponse(Object... dto) {
        log.info("resultResponse:" + JSON.toJSONString(dto));
        if (null != dto && dto.length > 0) {
            return ResultModel.success(dto[0]);
        } else {
            return ResultModel.success(null);
        }
    }

    public ResultModel resultResponse(ContentModel... contentModel) {
        log.info("resultResponse:" + JSON.toJSONString(contentModel));
        if (null != contentModel && contentModel.length > 0) {
            return ResultModel.success(contentModel[0]);
        } else {
            return ResultModel.success(null);
        }
    }

    protected ResultModel resultResponseSuccess(ContentModel... contentModel) {
        if (null != contentModel && contentModel.length > 0) {
            contentModel[0]
                    .setResult(RESTFUL_COMMON_KEY.CONTENTMODEL_SUCCESS_STATE);
            log.info("resultResponseSuccess:" + JSON.toJSONString(contentModel));
            return ResultModel.success(contentModel[0]);
        } else {
            log.info("resultResponseSuccess:" + JSON.toJSONString(contentModel));
            return ResultModel.success(null);
        }
    }

    protected ResultModel resultResponseFault(ContentModel... contentModel) {
        if (null != contentModel && contentModel.length > 0) {
            contentModel[0]
                    .setResult(RESTFUL_COMMON_KEY.CONTENTMODEL_FAULT_STATE);
            log.info("resultResponseFault:" + JSON.toJSONString(contentModel));
            return ResultModel.success(contentModel[0]);
        } else {
            log.info("resultResponseFault:" + JSON.toJSONString(contentModel));
            return ResultModel.success(null);
        }
    }

    protected UserModel getUserModel(String userStr, ContentModel contentModel) throws Exception{
        if(StringUtils.isBlank(userStr)) {
            contentModel.setResult(RESTFUL_COMMON_KEY.CONTENTMODEL_FAULT_STATE);
            contentModel.setResultMessage("请求参数为空");
            return null;
        }
        UserModel userModel = JSON.toJavaObject(JSON.parseObject(userStr), UserModel.class);
        if(userModel == null) {
            contentModel.setResult(RESTFUL_COMMON_KEY.CONTENTMODEL_FAULT_STATE);
            contentModel.setResultMessage("请求参数不全");
            return null;
        }
        return userModel;
    }
}
